<template>
  <el-row :gutter="20" v-if="!showcz">
    <el-col :span="8" :offset="8">
      <h2>吾圈登录</h2>
      <el-form :label-position="labelPosition" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="服务器ID">
          <el-input v-model="serveID" />
        </el-form-item>
        <el-form-item label="卡密">
          <el-input v-model="kakaka" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
  <el-row :gutter="20" v-if="showcz">
    <el-col :span="16" :offset="4">
      <el-descriptions title="20期组合出现的次数" :column="5" border>
        <el-descriptions-item label="大单">{{ dd }}</el-descriptions-item>
        <el-descriptions-item label="大双">{{ ds }}</el-descriptions-item>
        <el-descriptions-item label="小单">{{ xd }}</el-descriptions-item>
        <el-descriptions-item label="小双">{{ xs }}</el-descriptions-item>
        <el-descriptions-item label="开奖倒计时">{{ dTime }}</el-descriptions-item>
      </el-descriptions>
      <el-tabs type="border-card" class="demo-tabs">
        <el-tab-pane label="基础设置">
          <el-row ::gutter="20">
            <el-col :span="12">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span style="font-size: large;">{{ xuanzhong }}</span>
                  </div>
                </template>
                <el-table :data="groupList" ref="singleTableRef" highlight-current-row
                  @current-change="handleSelectionChange">
                  <el-table-column property="groupID" label="群ID" width="120" />
                  <el-table-column property="name" label="群名称" />
                </el-table>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span style="font-size: large;">下注设置</span>
                  </div>
                </template>

                <el-form label-position="left" label-width="100px">
                  <el-form-item label="选择组合">
                    <el-checkbox-group v-model="checkList" @change="change">
                      <el-checkbox label="小单大双" />
                      <el-checkbox label="小双大单" />
                    </el-checkbox-group>
                  </el-form-item>
                  <el-form-item label="选择模式">
                    <el-radio-group v-model="radio">
                      <el-radio :label="0">20期内热门</el-radio>
                      <el-radio :label="1">20期内冷门</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="开启倍投">
                    <el-switch v-model="isstart" />
                  </el-form-item>
                  <el-form-item label="小单大双倍投金额">
                    <el-input v-model="dsxd" type="textarea" />
                  </el-form-item>
                  <el-form-item label="小双大单倍投金额">
                    <el-input v-model="ddxs" type="textarea" />
                  </el-form-item>
                  <el-form-item label="小单大双赔率">
                    <el-input v-model="dsxdpl" />
                  </el-form-item>
                  <el-form-item label="小双大单赔率">
                    <el-input v-model="ddxspl" />
                  </el-form-item>
                  <el-form-item label="账单初始分">
                    <el-input v-model="zhangdan" />
                  </el-form-item>
                  <el-form-item>
                  <el-button type="primary" @click="baocun">保存</el-button>
                </el-form-item>
                </el-form>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="开奖下注记录">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-table :data="kjdata" style="width: 100%">
                <el-table-column prop="qihao" label="期号" />
                <el-table-column prop="drawDate" label="时间" />
                <el-table-column prop="LotResultNo" label="开奖结果" />
                <el-table-column prop="zh" label="开奖组合" />
              </el-table>
            </el-col>
            <el-col :span="12">
              <el-table :data="xiazhu" style="width: 100%" max-height="750">
                <el-table-column prop="issue" label="期号" />
                <el-table-column prop="text" label="下注" />
                <el-table-column prop="jine" label="金额" />
                <el-table-column prop="datey" label="时间" />
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="历史下注记录">
          <el-row :gutter="20">
            <el-col :span="24">
              <el-button type="primary" @click="seeAll">查看全部下注</el-button>
            <el-button type="success" @click="seedsxd">查看大双小单下注</el-button>
            <el-button type="danger" @click="seeddxs">查看大单小双下注</el-button>
              <el-table :data="xiazhull" style="width: 100%" max-height="750">
                <el-table-column prop="issue" label="期号" />
                <el-table-column prop="text" label="下注" />
                <el-table-column prop="jine" label="金额" />
                <el-table-column prop="datey" label="时间" />
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-col>
  </el-row>
</template>

<script>

import axios from 'axios'
import { ElMessage } from 'element-plus'
import TencentCloudChat from '@tencentcloud/chat'
import CryptoJS from 'crypto-js';
import { openDB } from 'idb';
import moment from 'moment';
import Worker from 'worker-loader!./woker.js'
export default {
  name: 'App',
  data() {
    return {
      name: "hello",
      username: "",
      password: "",
      kakaka:"",
      serveID: "",
      ddxs: [40, 65, 108, 158, 205, 285, 378, 479, 630, 820, 1052, 1370, 1790, 2320, 3015, 3920, 5115],
      dsxd: [50, 75, 128, 205, 330, 420, 600, 810, 1100, 1502, 2054, 2805, 3835, 5250, 7195, 9857, 13530, 18560],
      appid: "",
      imappid: 0,
      token: "",
      chat: null,
      buzhong: 0,// 不中的次数
      isstart: false,// 是否开启倍投
      dqzh: '',// 当前倍投的组合
      dqissue: 0,
      xuanzhong: '请选择群',
      xuanGroupList: [],
      groupList: [],
      showcz: false,
      Crypto: CryptoJS.enc.Utf8.parse("666888\0\0\0\0\0\0\0\0\0\0"),
      dbName: 'my-database',
      kjdata: [],
      dd: 0,
      xd: 0,
      ds: 0,
      radio:0,
      xs: 0,
      worker: new Worker(),
      dTime: 0,
      idb: null,
      checkList: [],
      newissue:0,
      xiazhu:[],
      istouzhu:false,
      dsxdpl:3.6,
      ddxspl:4.2,
      zhangdan:0,
      xiazhull:[],
      kakacreate_at:null,
      ruanjianDtime:null
    }
  },
  watch: {
    xuanGroupList(newV, old) {
      this.xuanzhong = '选择了:' + newV.name
      console.log(old)
      this.disabled = false
    },
  },
  created() {
    this.idb = openDB(this.dbName, 1, {
      upgrade(db) {
        db.createObjectStore('myinfo');
        db.createObjectStore('num');
        db.createObjectStore('xiazhu');
      }
    })
    this.getItems('myinfo').then(res => {
      if (res.length != 0) {
        this.username = res[0].userName
        this.password = res[0].password
        this.serveID = res[0].serverId
        this.kakaka = res[0].kakaka
      } else {
        this.username = ""
        this.password = ""
        this.serveID = ""
        this.kakaka = ""
      }
    })
    this.getItems('num').then(res => {
      if (res.length != 0) {
        this.checkList = res[0].checklist
        this.ddxs = res[0].jine.ddxs.split(",")
        this.dsxd = res[0].jine.dsxd.split(",")
        this.ddxspl = res[0].ddxspl
        this.dsxdpl = res[0].dsxdpl
        this.radio = res[0].radio
        this.zhangdan = res[0].zhangdan
      } else {
        this.checkList = []
        this.ddxs = [40, 65, 108, 158, 205, 285, 378, 479, 630, 820, 1052, 1370, 1790, 2320, 3015, 3920, 5115]
        this.dsxd = [50, 75, 128, 205, 330, 420, 600, 810, 1100, 1502, 2054, 2805, 3835, 5250, 7195, 9857, 13530, 18560]
        this.ddxspl = 4.2
        this.dsxdpl = 3.6
        this.radio = 0
        this.zhangdan = 0
      }
    })
    this.getItems('xiazhu').then(res => {
      if (res.length != 0) {
        let count = res.length 
        for (let i = res.length-1; i >= 0 && count > 0; i--) {
          this.xiazhu.push(res[i])
          count--; // 每次循环减少计数
          if (count === 0) break; // 当达到指定次数时退出循环
        }
      } else {
        this.xiazhu = []
      }
    })
  },
  mounted() {
    this.getkj()
    this.workerF()
  },
  methods: {
    seeAll(){
      this.xiazhull = this.xiazhu
    },
    seeddxs(){
      this.xiazhull = this.xiazhu.filter(item=>
        item.text == '大单' || item.text == '小双'
      )
    },
    seedsxd(){
      this.xiazhull = this.xiazhu.filter(item=>
        item.text == '大双' || item.text == '小单'
      )
    },
    change(){
      console.log(this.checkList)
    },
    // 添加记录
    baocun(){
      let config = {
        jine:{
          ddxs:this.ddxs.join(','),
          dsxd:this.dsxd.join(',')
        },
        checklist:this.checkList,
        ddxspl:this.ddxspl,
        dsxdpl:this.dsxdpl,
        radio:this.radio,
        zhangdan:this.zhangdan
      }
      this.updateItem('num',JSON.parse(JSON.stringify(config)),1)
      ElMessage({
                message: '保存成功',
                type: 'success',
              })
      setTimeout(()=>{
        this.getItems('num').then(res => {
          if (res.length != 0) {
            this.checkList = res[0].checklist
            this.ddxs = res[0].jine.ddxs.split(",")
            this.dsxd = res[0].jine.dsxd.split(",")
            this.ddxspl = res[0].ddxspl
            this.dsxdpl = res[0].dsxdpl
            this.radio = res[0].radio
            this.zhangdan = res[0].zhangdan
          } else {
            this.checkList = []
            this.ddxs = [40, 65, 108, 158, 205, 285, 378, 479, 630, 820, 1052, 1370, 1790, 2320, 3015, 3920, 5115]
            this.dsxd = [50, 75, 128, 205, 330, 420, 600, 810, 1100, 1502, 2054, 2805, 3835, 5250, 7195, 9857, 13530, 18560]
            this.ddxspl = 4.2
            this.dsxdpl = 3.6
            this.radio = 0
            this.zhangdan = 0
          }
        })
      },500)
    },
    async addItem(dataname, item, id) {
      let create_at = moment().format('YYYY-MM-DD HH:mm:ss')
      let update_at = moment().format('YYYY-MM-DD HH:mm:ss')
      item.create_at = create_at
      item.update_at = update_at
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.add(item, id);
    },
    // 查询记录
    async getItems(dataname) {
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readonly');
      const store = tx.objectStore(dataname);
      return store.getAll();
    },
    // 删除记录
    async deleteItem(dataname, id) {
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.delete(id);
    },
    // 更新记录
    async updateItem(dataname, updates, id) {
      const db = await this.idb;
      const tx = db.transaction(dataname, 'readwrite');
      const store = tx.objectStore(dataname);
      store.put({ ...updates }, id);
    },
    workerF() {
      this.worker.postMessage({
        type: "start",
        interval: 1000
      })
      this.worker.onmessage = (event) => {
        // 收息消息
        if (event.data.type == 'message') {
          this.dTime--;
          if (parseInt(this.dTime) <= 0 && parseInt(this.dTime) % 5 == 0) {
            // 封盘
            this.getkj()
          }
          // 判断上期倍投是否正确
          if(this.dTime >=90 && !this.istouzhu && this.dTime <=180){
            // 开奖了
            if(this.isstart){
              if(this.dqzh!='' && this.xiazhu.length!=0){
                // 正在倍投
                // 判断上期是否中奖
                if(this.xiazhu[0].issue == this.newissue){
                  if(this.dqzh == this.kjdata[0].zh){
                    // 中奖
                    
                      if(this.dqzh=="小双" || this.dqzh=="大单"){
                        this.zhangdan = parseFloat(this.zhangdan)+(this.ddxs[this.buzhong]*this.ddxspl)
                      }else{
                        this.zhangdan = parseFloat(this.zhangdan)+(this.dsxd[this.buzhong]*this.dsxdpl)
                      }
                    this.buzhong = 0
                    this.dqzh = this.getMinZh(this.dd,this.ds,this.xd,this.xs)
                    this.xiazhuy()
                  }else{
                    // 不中
                    if(this.xiazhu[0].issue == this.newissue){
                      this.buzhong++
                      this.xiazhuy()
                    }else{
                      this.buzhong = 0
                      this.dqzh = this.getMinZh(this.dd,this.ds,this.xd,this.xs)
                      this.xiazhuy()
                    }
                  }
                }else{
                    this.buzhong = 0
                    this.dqzh = this.getMinZh(this.dd,this.ds,this.xd,this.xs)
                    this.xiazhuy()
                } 
              }else{
                // 没有倍投
                // 加入倍投
                this.buzhong = 0
                this.dqzh = this.getMinZh(this.dd,this.ds,this.xd,this.xs)
                this.xiazhuy()
              }
            }
          }
        }
      }
    },
    handleSelectionChange(list) {
      this.xuanGroupList = list
    },
    onSubmit() {
      let data = {
        userName: this.username,
        password: this.password,
        serverId: this.serveID,
        kakaka:this.kakaka
      }
      axios.get('https://xq.ts28.com.cn/getka?kaka='+this.kakaka).then(res=>{
        if(res.data.code == 200){
          this.kakacreate_at = res.data.data.create_at
          let creDate = moment(this.kakacreate_at).add(30,'day').format('YYYY-MM-DD HH:mm:ss')
          this.ruanjianDtime = creDate
          let thisDate = moment()
          if(!thisDate.diff(creDate,'days')>=0){
            axios.post("https://api.ts28.com.cn/wqlogin", data).then(res => {
              if (res.data.code == 200) {
                this.appid = res.data.data.accid
                this.token = res.data.data.token
                this.imappid = parseInt(res.data.data.imAppid)
                this.chat = TencentCloudChat.create(
                  {
                    SDKAppID: this.imappid
                  }
                )
                this.chat.login({
                  userID: this.appid,
                  userSig: this.token
                }).then(res => {
                  if (res.data.repeatLogin === true) {
                    // 标识账号已登录，本次登录操作为重复登录
                    ElMessage({
                      message: '登录失败，重复登录，请先退出',
                      type: 'error',
                    })
                    this.chat.destroy()
                    this.onSubmit()
                  } else {
                    setTimeout(() => {
                      this.chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, this.getMsg)
                      this.chat.on(TencentCloudChat.EVENT.KICKED_OUT, this.onKickedOut)
                      this.chat.getGroupList().then(imResponses => {
                        this.groupList = imResponses.data.groupList
                        this.showcz = true
                      }).catch(imError => {
                        console.warn('getGroupList error:', imError); // 获取群组列表失败的相关信息
                      })
                    }, 1000)
                    ElMessage({
                      message: '登录成功',
                      type: 'success',
                    })
                    this.updateItem('myinfo', data, 1)
                  }
                }).catch(err => {
                  ElMessage({
                    message: err,
                    type: 'error',
                  })
                })
              } else {
                ElMessage({
                  message: '登录失败，' + res.data.data.msg,
                  type: 'error',
                })
              }
            }).catch(err => {
              console.log(err)
            })
          }else{
            ElMessage({
                  message: '登录失败，卡密过期' ,
                  type: 'error',
                })
          }
        }else{
          ElMessage({
                  message: '登录失败，卡密不存在' ,
                  type: 'error',
                })
        }
      })
    },
    onKickedOut(event){
      console.log(event.data.type)
      this.chat.destroy()
      this.onSubmit()

    },
    getMsg(event) {
      const messageList = event.data
      messageList.forEach(message => {
        if (message.type === TencentCloudChat.TYPES.MSG_TEXT && this.xuanGroupList.groupID === message.to) {
          let msg = this.textPa(message.payload.text)
          console.log(msg)
        }
      })
    },
    textPa(bastr) {
      let srcs = bastr;
      let decrypt = CryptoJS.AES.decrypt(srcs, this.Crypto, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      return decrypt.toString(CryptoJS.enc.Utf8)
    },
    xiazhuy(){
      // 判断是否选中群
      let jine = 0
        if(this.dqzh == '小单' || this.dqzh == '大双'){
          if(this.buzhong < this.dsxd.length){
            // 可以继续
            jine = this.dsxd[this.buzhong]
          }else{
            this.isstart = false
            return false
          }
        }
        if(this.dqzh == '大单' || this.dqzh == '小双'){
          if(this.buzhong < this.ddxs.length){
            // 可以继续
            jine = this.ddxs[this.buzhong]
          }else{
            this.isstart = false
            return false
          }
        }
        if(parseFloat(jine)>parseFloat(this.zhangdan)){
          ElMessage({
            message: '金额不足',
            type: 'error',
          })
          this.isstart = false
          return false
        }
      let msg = this.dqzh+jine.toString()
      if(this.xiazhu.length!=0){
        if(this.xiazhu[0].issue == this.newissue+1){
          return false;
        }
      }
      if(this.xuanGroupList.groupID && this.chat!=null){
        let message = this.chat.createTextMessage({
          to: this.xuanGroupList.groupID,
          conversationType: TencentCloudChat.TYPES.CONV_GROUP,
          payload: {
            text: msg
          },
        });
        // 2. 发送消息
        let promise = this.chat.sendMessage(message);
        promise.then((imResponse)=> {
          // 发送成功
          // 下注成功
          // 加入数据库
          let data = {
            issue:this.dqissue,
            text:this.dqzh,
            jine:jine,
            datey:moment().format('YYYY-MM-DD HH:mm:ss')
          }
          this.addItem('xiazhu',data,this.dqissue)
          this.istouzhu = true
          this.zhangdan = parseFloat(this.zhangdan)-parseFloat(jine)
          this.xiazhu.unshift(data)
          this.baocun()
          ElMessage({
            message: '下注成功，下注:'+msg,
            type: 'success',
          })
          console.log(imResponse)
        }).catch(function(imError) {
          // 发送失败
          console.warn('sendMessage error:', imError);
        });
      }else{
        ElMessage({
            message: '没有选择群',
            type: 'error',
          })
      }

    },
    getkj() {
      this.ds = 0
      this.dd = 0
      this.xd = 0
      this.xs = 0
      axios.get("https://api.kkaakj.com/open/history?game=Canadian").then(res => {
        this.kjdata = []
        if (res.data.resultCode) {
          for (let index = 0; index < 20; index++) {
            this.kjdata.push(res.data.data[res.data.data.length-1-index])
            let numc4 = parseInt(this.kjdata[index].num[0])+parseInt(this.kjdata[index].num[1])+parseInt(this.kjdata[index].num[2])
            this.kjdata[index].LotResultNo = this.kjdata[index].num[0]+" + " +this.kjdata[index].num[1]+" + "+this.kjdata[index].num[2]+" = "+numc4
            this.kjdata[index].zh = this.getzh(numc4)
            if (this.kjdata[index].zh == "大双") {
              this.ds++;
            }
            if (this.kjdata[index].zh == "大单") {
              this.dd++;
            }
            if (this.kjdata[index].zh == "小双") {
              this.xs++;
            }
            if (this.kjdata[index].zh == "小单") {
              this.xd++;
            }
          }
          this.newissue = parseInt(this.kjdata[0].qihao)
          if(this.dqissue == 0 ){
            this.dqissue = parseInt(this.kjdata[0].qihao)+1
          }
          if(this.newissue == this.dqissue){
            // 开奖
            this.dqissue = this.newissue + 1
            this.istouzhu = false
          }
          let newkjdate = moment(this.kjdata[0].drawDate).format("YYYY-MM-DD HH:mm:ss")
          let nextkjdate = moment(newkjdate).add(210, 'seconds')
          this.dTime = nextkjdate.diff(moment(new Date()), 'seconds')
        } else {
          ElMessage({
            message: '获取开奖失败，请重试',
            type: 'error',
          })
        }
      })
    },
    getzh(str) {
      let num = parseInt(str)
      if (num < 14) {
        // 小
        if (num % 2 == 0) {
          // 双
          return '小双'
        } else {
          // 单
          return '小单'
        }
      } else {
        // 大
        if (num % 2 == 0) {
          // 双
          return '大双'
        } else {
          // 单
          return '大单'
        }
      }
    },
    getMinZh(dd,ds,xd,xs){
      if(this.radio == 0){
        // 热门
        if(this.checkList.length == 2){
        let min = Math.max(dd, ds, xd, xs);
        if (dd === min) {
            return '大单'
        } else if (ds === min) {
            return '大双'
        } else if (xd === min) {
            return '小单'
        } else if (xs === min) {
            return '小双'
        }
      }else{
        if(this.checkList[0]=="小单大双"){
          if(ds>xd){
            return '大双'
          }else{
            return '小单'
          }
        }else{
          if(dd>xs){
            return '大单'
          }else{
            return '小双'
          }
        }
      }
      }else{
        // 冷门
        if(this.checkList.length == 2){
        let min = Math.min(dd, ds, xd, xs);
        if (dd === min) {
            return '大单'
        } else if (ds === min) {
            return '大双'
        } else if (xd === min) {
            return '小单'
        } else if (xs === min) {
            return '小双'
        }
      }else{
        if(this.checkList[0]=="小单大双"){
          if(ds<xd){
            return '大双'
          }else{
            return '小单'
          }
        }else{
          if(dd<xs){
            return '大单'
          }else{
            return '小双'
          }
        }
      }
      }

    }
  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 20px;
}
</style>
